package com.chenjt.juc.thirteen_readWriteLock;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyResource{// 资源类，模拟一个简单的缓存
    Map<String,String> map = new HashMap<>();
    // ReentrantLock 等价于 synchronized
    Lock lock = new ReentrantLock();
    // ReentrantReadWriteLock 一体两面，读写互斥，读读共享
    ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key,String value){
//        lock.lock();
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"正在写入");
            map.put(key,value);
            TimeUnit.MILLISECONDS.sleep(500);
            System.out.println(Thread.currentThread().getName()+"\t"+"完成写入");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            lock.unlock();
            rwLock.writeLock().unlock();
        }
    }


    public void read(String key){
//        lock.lock();
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"正在读取");
            String result = map.get(key);
//            TimeUnit.MILLISECONDS.sleep(200);
            TimeUnit.MILLISECONDS.sleep(2000);
            System.out.println(Thread.currentThread().getName()+"\t"+"完成读取"+"\t"+result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            lock.unlock();
            rwLock.readLock().unlock();
        }
    }


}

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/24 9:36
 */
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource();

        for (int i = 0; i <= 10; i++) {
            int finalI = i;
            new Thread(()->{
                myResource.write(finalI+"",finalI+"");
            },String.valueOf(i)).start();
        }


        for (int i = 0; i <= 10; i++) {
            int finalI = i;
            new Thread(()->{
                myResource.read(finalI+"");
            },String.valueOf(i)).start();
        }



        // 读方法中暂停两秒，演示读锁还没完成，写锁无法获得
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i <= 3; i++) {
            int finalI = i;
            new Thread(()->{
                myResource.write(finalI+"",finalI+"");
            },"新写锁-》"+String.valueOf(i)).start();
        }

    }


}
